import aiohttp
from sjudger.config import *
from sjudger.common import *
import asyncio
import logging as log
heartbeat_run=True
async def heartbeat_loop():
    global heartbeat_run
    log.info("[HEARTBEAT] Heartbeat mainloop ")
    while heartbeat_run:
        await asyncio.sleep(HEARTBEAT_INTERVAL)
        log.info("[HEARTBEAT] Heartbeat begins")
        async with aiohttp.ClientSession() as session:
            data:HeartbeatRequest={"name":WORKER_NAME}
            ok_cnt=0
            for i in HEARTBEAT_URLS:
                log.info(f"[HEARTBEAT] sending {i}")
                try:
                    async with session.post(i,json=data,timeout=HEARTBEAT_TIMEOUT) as response:
                        data:NormalResponse=response.json()
                        if response.status!=200:
                            raise ValueError(f"Remote host responding with code {response.status}")
                        if data["error"]!=ErrorCode.OK:
                            raise ValueError(f"Romote host returned a failed status {data['error']}")
                        ok_cnt+=1
                except (TimeoutError,aiohttp.ServerTimeoutError,aiohttp.ConnectionTimeoutError) as e:
                    log.error(f"[HEARBEAT] Remote host timeout")
                    log.debug(f"> {e}")
                except ValueError as e:
                    log.error(f"[HEARTBEAT] Remote host responded with a not ok status")
                    log.debug(f"> this {e}")
            log.info(f"[HEARTBEAT] Completed. {ok_cnt}/{len(HEARTBEAT_URLS)} succeeded")

